package com.tf.xx.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tf.xx.entity.EduSubject;
import com.tf.xx.entity.excel.SubjectData;
import com.tf.xx.exception.MyException;
import com.tf.xx.service.EduSubjectService;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    private EduSubjectService eduSubjectService;

    public SubjectExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        //表示excel中没有数据，就不需要读取了
        if (subjectData == null) {
            throw new MyException(20001, "文件数据为空");
        }



        EduSubject existOneSubject = this.existOneSubject(eduSubjectService, subjectData.getOneSubjectName());
        if(existOneSubject ==null)

        {    //没有相同的一级分类。进行添加
            existOneSubject = new EduSubject();
            existOneSubject.setParentId("0");
            existOneSubject.setTitle(subjectData.getOneSubjectName());
            eduSubjectService.save(existOneSubject);
        }

        //获取一级分类的id值
        String parent_id = existOneSubject.getId();

        //判断一级分类不能重复添加
        EduSubject existTwoSubject = this.existTwoSubject(eduSubjectService, subjectData.getTwoSubjectName(), parent_id);
        if(existTwoSubject ==null)

        {
            existTwoSubject = new EduSubject();
            existTwoSubject.setParentId(parent_id);
            existTwoSubject.setTitle(subjectData.getTwoSubjectName());
            eduSubjectService.save(existTwoSubject);
        }

    }




    private EduSubject existOneSubject(EduSubjectService eduSubjectService, String name) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name)
                .eq("parent_id", "0");
        EduSubject oneSubject = eduSubjectService.getOne(wrapper);
        return eduSubjectService.getOne(wrapper);
    }

    private EduSubject existTwoSubject(EduSubjectService eduSubjectService, String name, String parent_id) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name)
                .eq("parent_id", parent_id);
        EduSubject twoSubject = eduSubjectService.getOne(wrapper);
        return eduSubjectService.getOne(wrapper);
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {


    }


}
